package com.bgds.sys.data.iXCom29d.gateway.impl;

import cn.hutool.core.util.NumberUtil;
import com.bgds.sys.common.utils.HexUtil;
import com.cisdi.data.common.exception.BusinessException;
import io.netty.buffer.ByteBuf;

import java.nio.charset.Charset;
/**
 * @author
 * 解码
 */
public class BaoXingVoDecode {
    //电文前部分长度
	private static final int PRE_LENGTH=30;

	public static BaoXingVo decode(ByteBuf bufferIn, Charset charset) {
        byte[] headerBytes = new byte[29];
        bufferIn.readBytes(headerBytes);
        String header = new String(headerBytes, charset);
        //请求头截取
        // 解析teleLength
        String lendthString = getString(header, 0, 4);
        String msgKey = getString(header, 4, 10);
        String date = getString(header, 10, 24);
        String time = getString(header, 24, 28);
        String funcCode = getString(header, 28, 29);
        int totalLength = NumberUtil.parseInt(lendthString);
        
        BaoXingVo result = new BaoXingVo();
        result.setLength(totalLength);
        result.setMsgKey(msgKey);
        result.setDate(date);
        result.setTime(time);
        result.setFuncCode(funcCode.charAt(0));
        //请求体
        if(totalLength > PRE_LENGTH) {
        	int bodyLength = totalLength - PRE_LENGTH;
        	byte[] bodyBytes = new byte[bodyLength];
        	bufferIn.readBytes(bodyBytes);
        	String body = new String(bodyBytes, charset);
        	result.setBody(body);
        	result.setData(bodyBytes);
        }
        
        // 读取结束符
        byte endByte = bufferIn.readByte();
        if(BaoXingConsts.MSG_END_BYTE != endByte) {
        	throw new BusinessException(" msg end byte is " + endByte + " not valid.");
        }
        return result;
	}
	
	private static String getString(String header, int start, int end) {
		char[] dst = new char[end - start];
		header.getChars(start, end, dst, 0);
		
		return new String(dst);
	}


    public static float byte2float(byte[] b) {
        int l;
        l = b[0];
        l &= 0xff;
        l |= ((long) b[1] << 8);
        l &= 0xffff;
        l |= ((long) b[2] << 16);
        l &= 0xffffff;
        l |= ((long) b[3] << 24);
        return Float.intBitsToFloat(l);
    }
}
